package cn.marinda.totipotentwar.global;

import cn.marinda.totipotentwar.TotipotentWar;
import com.google.common.base.Charsets;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 抽象插件配置
 *
 * @author hwj
 * @date 2022/01/26
 */
public abstract class AbstractPluginConfig implements PluginConfig{
    /**
     * 配置
     */
    public FileConfiguration config;
    public String configName;
    /**
     * 摘要插件配置
     *
     * @param newConfigName 配置名称
     */
    public AbstractPluginConfig(String newConfigName){
        newConfigDefault(newConfigName);
    }

    /**
     * 新的配置默认
     *
     * @param newConfigName 新的配置名称
     */
    private void newConfigDefault(String newConfigName){
        String newFiles = newConfigName + ".yml";
        this.configName = newFiles;
        try{
            File file = new File(TotipotentWar.plugin.getDataFolder(),configName);
            FileConfiguration newConfig = YamlConfiguration.loadConfiguration(file);
            this.config = newConfig;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 默认数据
     */
    protected abstract void defaultData();
    /**
     * 摘要插件配置
     *
     * @param plugin 插件
     */
    public AbstractPluginConfig(Plugin plugin){
        this.config = plugin.getConfig();
    }

    /**
     * 设置配置
     *
     * @param key   关键
     * @param value 价值
     */
    @Override
    public void setConfig(String key, Object value) {
        config.set(key,value);
    }

    @Override
    public void reload(String configName) {
        config = YamlConfiguration.loadConfiguration(new File(TotipotentWar.plugin.getDataFolder(),configName));

        final InputStream defConfigStream = TotipotentWar.plugin.getResource(configName);
        if (defConfigStream == null) {
            return;
        }

        config.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream, Charsets.UTF_8)));
    }

    /**
     * 保存配置
     *
     * @return boolean
     */
    @Override
    public void saveConfig() {
        try {
            config.save(configName);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 读取字符串
     *
     * @param str str
     * @return {@link String}
     */
    protected String readString(String str){
        return config.getString(str);
    }

    /**
     * 阅读列表
     *
     * @param str str
     * @return {@link List}<{@link String}>
     */
    protected List<String> readList(String str){
        return config.getStringList(str);
    }

    /**
     * 读int
     *
     * @param str str
     * @return int
     */
    protected int readInt(String str){
        return config.getInt(str);
    }
}
